package db

import (
	"fmt"
	"gitee.com/huanfion/urlshortener/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

var SqlSession *gorm.DB

func init() {
	//dsn := "root:pids@PCI2020@tcp(172.25.10.146:3306)/gz_cocc?charset=utf8mb4&parseTime=True&loc=Local"
	dbconfig := config.Cfg.Database
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbconfig.User, dbconfig.Password, dbconfig.Host, dbconfig.Port, dbconfig.DBName)
	SqlSession, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			TablePrefix:   ""},
		Logger:      logger.Default.LogMode(logger.Info),
		PrepareStmt: true,
	})

	if err != nil {
		log.Println("数据库连接失败", err.Error())
		panic(fmt.Sprintf("failed to connect to database: %v", err))
	}
	//根据*grom.DB对象获得*sql.DB的通用数据库接口
	sqlDb, err := SqlSession.DB()
	if err != nil {
		log.Println("获取通用数据库接口失败", err.Error())
		panic(fmt.Sprintf("获取通用数据库接口失败: %v", err))
	}
	sqlDb.SetMaxOpenConns(dbconfig.MaxOpenConns)
	sqlDb.SetMaxIdleConns(dbconfig.MaxIdleConns)
	sqlDb.SetConnMaxLifetime(time.Hour)
}
